import {
  indexBuilder,
  indexPaginateBuilder,
  showBuilderEntity,
} from '@libs/common/repository';
import { Inject, Injectable } from '@nestjs/common';
import { ArrayToTree } from '@shencom/utils-array';
import { FindOptionsSelect, FindOptionsWhere, Repository } from 'typeorm';

import { ProviderKey } from './department.providers';
import {
  DepartmentIndexDto,
  DepartmentShowDto,
  FindDepartmentDto,
} from './dto/department.dto';
import { Department } from './entities/department.entity';

@Injectable()
export class DepartmentService {
  @Inject(ProviderKey)
  private repository: Repository<Department>;

  async tree(dto: DepartmentIndexDto) {
    const tree = await indexBuilder({
      dto,
      repository: this.repository,
    }).getMany();

    const res = ArrayToTree(
      tree.filter((item) => item.active === 1),
      { pid: 'parentId' },
    );
    return res;
  }

  async index(dto: DepartmentIndexDto) {
    const res = await indexPaginateBuilder({
      dto,
      repository: this.repository,
    });
    return res;
  }

  async show(dto: DepartmentShowDto) {
    return showBuilderEntity(this.repository, dto);
  }

  async find(dto?: FindDepartmentDto, select?: FindOptionsSelect<Department>) {
    const where: FindOptionsWhere<Department> = dto || {};

    where.active = 1;

    return this.repository.find({ where, select });
  }
}
